﻿using System;
using Microsoft.Phone.BackgroundTransfer;
using System.IO.IsolatedStorage;

namespace DataService
{
    //DEMOSTOP#3 
    public class LocalhostSync : ISyncProvider
    {
        //REQUIRES THE SERVER TO DEFINE A MIME TYPE: ".sdf" as "application/octet-stream"!
        const string serviceUploadLocationURL = "http://localhost/FileUploaderWcfRestService/UploaderService/File/";
        const string downloadLocationURL = "http://localhost/FileUploaderWcfRestService/Backups/";
        const string TransfersFiles = "transfers"; //Default download location
        const string downloadedDBName = "ToDo_NEW.sdf";
        const string localDBName = "ToDo.sdf";

        #region ISyncProvider Members

        public void Upload(string username, string password, string filename)
        {
            using (System.IO.IsolatedStorage.IsolatedStorageFile iso = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!iso.FileExists(localDBName))
                    return;

                iso.CopyFile(localDBName, "/" + TransfersFiles + "/" + localDBName, true);
            }

            BackgroundTransferRequest btr = new BackgroundTransferRequest(new Uri(serviceUploadLocationURL + localDBName, UriKind.Absolute));
            btr.TransferPreferences = TransferPreferences.AllowBattery;
            btr.Method = "POST";
            btr.UploadLocation = new Uri("/" + TransfersFiles + "/" + localDBName, UriKind.Relative);
            btr.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(btr_UploadTransferStatusChanged);
            btr.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(btr_TransferProgressChanged);
            Microsoft.Phone.BackgroundTransfer.BackgroundTransferService.Add(btr);
        }

        void btr_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        {
            bool isUploading = e.Request.TotalBytesToSend > 0 ? true : false;

            if (null != DownloadUploadProgress)
                DownloadUploadProgress(this,
                    new DownloadUploadProgressEventArgs(isUploading,
                                                        isUploading ? e.Request.BytesSent : e.Request.BytesReceived,
                                                        isUploading ? e.Request.TotalBytesToSend : e.Request.TotalBytesToReceive));
        }

        void btr_UploadTransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            if (e.Request.TransferStatus == Microsoft.Phone.BackgroundTransfer.TransferStatus.Completed)
            {
                using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (iso.FileExists(e.Request.UploadLocation.OriginalString))
                        iso.DeleteFile(e.Request.UploadLocation.OriginalString);
                }

                Microsoft.Phone.BackgroundTransfer.BackgroundTransferService.Remove(e.Request);

                if (null != e.Request.TransferError)
                {
                    //LOG error
                }
                else
                {
                    if (null != UploadFinished)
                        UploadFinished(this, new DownloadUploadFinishedEventArgs());
                }

            }
        }

        void btr_DownloadTransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine(e.Request.TransferStatus);

            if (e.Request.TransferStatus == Microsoft.Phone.BackgroundTransfer.TransferStatus.Completed)
            {
                Microsoft.Phone.BackgroundTransfer.BackgroundTransferService.Remove(e.Request);

                if (null != e.Request.TransferError)
                {
                    //LOG error
                }
                else
                {
                    //Overwrite the DB
                    using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        iso.CopyFile("/" + TransfersFiles + "/" + downloadedDBName, "/" + localDBName, true);
                        iso.DeleteFile("/" + TransfersFiles + "/" + downloadedDBName);

                        if (null != DownloadFinished)
                            DownloadFinished(this, new DownloadUploadFinishedEventArgs());
                    }
                }
            }
        }

        public void Download(string username, string password, string filename)
        {
            BackgroundTransferRequest btr = new BackgroundTransferRequest(
                new Uri(downloadLocationURL + localDBName, UriKind.Absolute),
                new Uri(TransfersFiles + @"\" + downloadedDBName, UriKind.Relative));
            btr.TransferPreferences = TransferPreferences.AllowBattery;
            btr.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(btr_DownloadTransferStatusChanged);
            btr.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(btr_TransferProgressChanged);
            BackgroundTransferService.Add(btr);
        }

        #endregion

        public delegate void DownloadFinishedEventHandler(object sender, DownloadUploadFinishedEventArgs e);
        public delegate void DownloadProgressEventHandler(object sender, DownloadUploadProgressEventArgs e);

        public event DownloadFinishedEventHandler DownloadFinished;
        public event DownloadFinishedEventHandler UploadFinished;
        public event DownloadProgressEventHandler DownloadUploadProgress;

    }
}
